package com.itheima.system.controller;

import com.baidu.aip.util.Base64Util;
import com.itheima.common.entity.Result;
import com.itheima.common.entity.ResultCode;
import com.itheima.system.service.FaceLoginService;
import com.itheima.system.service.UserService;
import com.itheima.system.utils.BaiDuAiUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author qiankaofei
 * @version 1.0
 * @date 2020/11/25 20:37
 */
@RestController
@RequestMapping("/sys/faceLogin")
public class FaceLoginController {

    @Autowired
    private BaiDuAiUtils baiDuAiUtils;

    @Autowired
    private FaceLoginService faceLoginService;


    @Autowired
    private UserService userService;


    /**
     * 获取刷脸登录二维码
     *  返回值: QRCode对象（code+二维码）
     */
    @RequestMapping(value = "/qrcode", method = RequestMethod.GET)
    public Result qrcode() throws Exception {
        return new Result(ResultCode.SUCCESS,faceLoginService.getQRCode());
    }

    /**
     * 检查二维码：登录页面轮询调用此方法，根据唯一标识code判断用户登录情况
     */
    @RequestMapping(value = "/qrcode/{code}", method = RequestMethod.GET)
    public Result qrcodeCeck(@PathVariable(name = "code") String code) throws Exception {
        return new Result(ResultCode.SUCCESS,faceLoginService.checkQRCode(code));
    }

    /**
     * 人脸登录：根据落地页随机拍摄的面部头像进行登录
     *                根据拍摄的图片调用百度云AI进行检索查找
     * 用户存在返回token字符串
     */
    @RequestMapping(value = "/{code}", method = RequestMethod.POST)
    public Result loginByFace(@PathVariable(name = "code") String code, @RequestParam(name = "file") MultipartFile attachment) throws Exception {
        String userId = faceLoginService.loginByFace(code, attachment);
        if(StringUtils.isNotBlank(userId)){
            return new Result(ResultCode.SUCCESS);
        }
        return new Result(ResultCode.FAIL);
    }

    /**
     * 图像检测，判断图片中是否存在面部头像
     */
    @RequestMapping(value = "/checkFace", method = RequestMethod.POST)
    public Result checkFace(@RequestParam(name = "file") MultipartFile attachment) throws Exception {
        String image= Base64Util.encode(attachment.getBytes());
        Boolean boo = baiDuAiUtils.faceCheck(image);
        if(BooleanUtils.isTrue(boo)){
            return new Result(ResultCode.SUCCESS);
        }
        return new Result(ResultCode.FAIL);
    }
}
